#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
重复用户名数据处理
"""
from bson import ObjectId
import copy
from pymongo import MongoClient

from conf.settings import CLOUDMONITOR_MONGODB, CLOUDMONITOR_DB


class RepeatUser(object):

    free_id = "616803d89601830541c28520"

    def __init__(self):
        self.db = MongoClient(CLOUDMONITOR_MONGODB)[CLOUDMONITOR_DB]
        self.username_list = self.repeat_user()

    def repeat_user(self):
        query = [{"$group": {"_id": "$username", "count": {"$sum": 1}}}, {"$match": {"count": {"$gt": 1}}}]
        username_list = []
        for item in self.db["users"].aggregate(query):
            username_list.append(item["_id"])
        return username_list

    def delete_other_data(self, del_uids):
        print(f"删除告警， 套餐相关多余数据, 用户ID {del_uids}")
        if not del_uids:
            return
        for table in ["alertgroups", "alertreceivers", "balances", "charges", ]:
            self.db[table].delete_many({"uid": {"$in": del_uids}})
        str_del_uid = [str(s) for s in del_uids]
        self.db["audits"].delete_many({"uid": {"$in": str_del_uid}})

    def update_user_data(self, save_user, del_uid):
        print(f"更新用户{save_user['username']}, 数据为 {save_user}")
        self.db["users"].update({"_id": save_user["_id"]}, {"$set": save_user})
        if del_uid:
            print(f"删除多余用户 {del_uid}")
            self.db["users"].delete_many({"_id": {"$in": del_uid}})

    def update_balance_data(self, package_user, save_user):
        self.db["balances"].update({"_id": package_user["balanceId"]}, {"$set": {"uid": save_user["_id"]}})
        self.db["charges"].update({"uid": package_user["_id"]}, {"$set": {"uid": save_user["_id"]}})

    def parse_user_data(self, job_uids, user_list):
        job_user = [u for u in user_list if u["_id"] in job_uids]
        not_free_user = [u for u in user_list if isinstance(u.get("planId"), ObjectId) and str(u["planId"]) != self.free_id]
        del_user_ids = []
        package_user = {}
        # 用户有套餐且有资产的时候， 看实际数据情况， 以有资产的用户数据为准
        if job_user and not_free_user:
            save_user = copy.copy(job_user[0])
            package_user = not_free_user[0]
        elif job_user and (not not_free_user):
            save_user = copy.copy(job_user[0])
        elif (not job_user) and not_free_user:
            save_user = copy.copy(not_free_user[0])
        else:
            save_user = copy.copy(user_list[0])
        for user in user_list:
            if user["_id"] != save_user["_id"]:
                del_user_ids.append(user["_id"])
            for key in ["phoneVerified", "emailVerified", "identified", "enableMfa", "realname", "qq",
                        "attribution", "email", "phone", "idCardNum", "address", "idCardNum", "wechat",
                        "disclaimerAgreeTime"]:
                if value := user.get(key, False):
                    save_user.update({key: value})
                if package_user:
                    save_user["balanceId"] = package_user["balanceId"]
                    save_user["planId"] = package_user["planId"]
        return package_user, save_user, del_user_ids

    def run(self):
        print("开始处理重复用户名数据......")
        if not self.username_list:
            print("没有重复用户名！！！")
            print("结束！！！")
            exit(-1)
        print(f"重复用户名包括 {self.username_list}")
        username_map = {}
        user_ids = []
        for user in self.db["users"].find({"username": {"$in": self.username_list}}):
            if not username_map.get(user["username"]):
                username_map[user["username"]] = [user]
            else:
                username_map[user["username"]].append(user)
            user_ids.append(user["_id"])
        job_uids = self.db["jobs"].distinct("uids", {"uid": {"$in": user_ids}})
        for username, user_list in username_map.items():
            package_user, save_user, del_user_ids = self.parse_user_data(job_uids, user_list)
            if package_user:
                print(f"{package_user['username']} 购买过正式套餐, 处理套餐数据")
                self.update_balance_data(package_user, save_user)
            self.update_user_data(save_user, del_user_ids)
            self.delete_other_data(del_user_ids)
        print("结束！！！")
        exit(-1)


if __name__ == "__main__":
    obj = RepeatUser()
    obj.run()
